﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using QuickURLShortner;
using QuickURLShortner.Common;
using QuickURLShortner.Common.Models;
using QuickURLShortner.Common.Utils;

namespace QuickURLShortner.Controllers
{
	[HandleError]
	public class HomeController : Controller
	{   
        public ActionResult Index(string query)
        {
            if (String.IsNullOrEmpty(query))
            {
                return View();
            }

            var DomainName = ConfigurationManager.AppSettings[UrlConstants.CONFIG_DOMAINNAME].ToString();
            Container oShortUrl = null;

            try
            {
                oShortUrl = Utils.RetrieveUrlFromDatabase(query);
                if (!(oShortUrl.RealUrl.Contains(Common.UrlConstants.COMMON_HTTP) || oShortUrl.RealUrl.Contains(UrlConstants.COMMON_HTTPS)))
                {
                    oShortUrl.RealUrl = UrlConstants.COMMON_HTTP + oShortUrl.RealUrl;
                }
                return Redirect(oShortUrl.RealUrl);

            }
            catch (Exception ex)
            {
                return View(UrlConstants.VIEW_ERROR);
            }
        }       
        /// <summary>
        /// Create New URL
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult UrlShortner(UrlModel model)
        {
            try
            {
                #region "Create"

                model.OrignalUrl = model.OrignalUrl.Replace(UrlConstants.COMMON_HTTP, "");

                var oShortUrl = new Container();

                oShortUrl.RealUrl = model.OrignalUrl;
                oShortUrl.ShortenedUrl = Utils.UniqueShortUrl();
                oShortUrl.CreateDate = DateTime.Now;
                oShortUrl.CreatedBy = "d4g";

                var dbShortURL = Utils.IsURLExists(oShortUrl.RealUrl);
               
                //Check URL exists or not
                if (string.IsNullOrEmpty(dbShortURL))
                    Utils.AddUrlToDatabase(oShortUrl);
                else
                    oShortUrl.ShortenedUrl = dbShortURL.Trim();  

                oShortUrl.ShortenedUrlCombo = Utils.PublicShortUrl(oShortUrl.ShortenedUrl);

                #endregion
                // TODO: Add insert logic here
                ViewData[UrlConstants.URL_PART1] = oShortUrl.ShortenedUrlCombo.FirstPart;
                ViewData[UrlConstants.URL_PART2] = oShortUrl.ShortenedUrlCombo.SecondPart;

                return View(UrlConstants.VIEW_INDEX);
            }
            catch (Exception ex)
            {
                // todo proper error logging 
                return View(UrlConstants.VIEW_INDEX);
            }
        }
        
	}
}
